if select(2, UnitClass("player")) ~= "DEATHKNIGHT" then return end

local GetRuneCooldown = GetRuneCooldown

local iconTextures = {
	"Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Blood",
	"Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Unholy",
	"Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Frost",
	"Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Death",
}

local function Rune_OnUpdate(self, elapsed)
	local start, duration, runeReady = GetRuneCooldown(self.id)
	local cooldown = self.cooldown

	if start > 0 and duration > 0 and not runeReady then
		cooldown:Show()
		cooldown:SetCooldown(start, duration)
	else
		cooldown:Hide()
		self:SetScript("OnUpdate", nil)
		shine:Show()
	end
end

local function Shine_OnUpdate(self, elapsed)
	local timeLeft = self.timeLeft - elapsed
	local alpha
	if timeLeft < 0 then
		if self.shineIn then
			self.shineIn = nil
			self.timeLeft = 0.5
			alpha = 1
		else
			alpha = 0
			self:Hide()
		end
	else
		if self.shineIn then
			alpha = 1 - timeLeft * 2
		else
			alpha = timeLeft * 2
		end
		self.timeLeft = timeLeft
	end
	self:SetAlpha(alpha)
end

local function Shine_OnShow(self)
	self.shineIn = true
	self.timeLeft = 0.5
	self:SetAlpha(0)

end

local function createRuneIcon(parent, id)
	local rune = CreateFrame("Frame", nil, parent)
	rune:SetWidth(24)
	rune:SetHeight(24)

	local texture = rune:CreateTexture(nil, "ARTWORK")
	rune.texture = texture
	texture:SetAllPoints()

	local shine = rune:CreateTexture(nil, "OVERLAY")
	rune.shine = shine
	shine:SetTexture("Interface\\ComboFrame\\ComboPoint")
	shine:SetAlphaMode("ADD")
	shine:Hide()
	shine:SetWidth(60)
	shine:SetWidth(35)
	shine:SetPoint("CENTER")
	shine:SetScript("OnUpdate", Shine_OnUpdate)
	shine:SetScript("OnShow", Shine_OnShow)

	local cooldown = CreateFrame("Cooldown", nil, rune, oUF_CooldownTemplate)
	rune.cooldown = cooldown
	cooldown:SetAllPoints()

	rune.id = id
	return rune
end

local function createRuneIcons(parent)
	for id = 1, 6 do
		local rune = createRuneIcon(parent, id)
		parent[id] = rune
		rune:SetPoint("TOPLEFT", (id - 1) * 24, 0)
	end
end

local function RUNE_POWER_UPDATE(self, event, ...)
	local id, usable = ...
	if not usable then
		local rune = self.Runes[id]
		rune:SetScript("OnUpdate", Rune_OnUpdate)
	end
end

local function RUNE_TYPE_UPDATE(self, event, ...)
	local id = ...
	local rune = self.Runes[id]
	local type = GetRuneType(id)
	local texture = rune.texture
	if type then
		texture:SetTexture(iconTextures[type])
		texture:Show()
	else
		texture:Show()
	end
end

oUF:RegisterInitCallback(function (self)

	local Runes = self.Runes
	if not Runes or self.unit ~= "player" then return end

	CreateRuneIcons(Runes)
	CreateRuneIcons = nil

	self:RegisterEvent("RUNE_POWER_UPDATE")
	self:RegisterEvent("RUNE_TYPE_UPDATE")

	self.RUNE_POWER_UPDATE = RUNE_POWER_UPDATE
	self.RUNE_TYPE_UPDATE = RUNE_TYPE_UPDATE
end)
